<template>
  <div class="teacher">
    <UserPageSearch
      :formConfig="teacherFormConfig"
      @handleNewClick="onHandleNewClick"
      @handleDownloadClick="onHandleDownloadClick"
    />
    <UserPageContent
      v-bind="teacherTableProps"
      ref="userPageContentRef"
      @pageInfoChange="onPageInfoChange"
      @handleEditClick="onHandleEditClick"
    />
    <UserFormModal
      ref="formModelRef"
      :defualtFormData="defualtModelFormData"
      :modelConfig="teacherModelConfig"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, provide, computed, onMounted, onBeforeMount, watch } from 'vue'
import { useStore } from 'vuex'
import UserPageSearch from '@/components/UserPageSearch/UserPageSearch.vue'
import UserPageContent from '@/components/UserPageContent/UserPageContent.vue'
import { teacherFormConfig, teacherTableProps, teacherModelConfig } from './config/teacher.config'
import UserFormModal from '@/components/UserFormModal'
import { usePageModal } from '@/hooks/usePageModal.js'

const store = useStore()
const userPageContentRef = ref(null)
const formValue = ref({
  // 下拉框值默认为“姓名”
  label: 'name',
  value: '',
  role: teacherFormConfig.userRole
})
const page = ref({
  page_num: 1,
  page_size: 10
})
// 当改变了表单信息，点击查询时触发的事件
const changeFormValue = (data) => {
  formValue.value = data
  userPageContentRef.value.getPageList(formValue.value, page.value)
}

provide('formValue', formValue.value)
provide('changeFormValue', changeFormValue)

// 页面刷新就触发，当分页的信息发生变化时，触发的事件
const onPageInfoChange = (pageInfo) => {
  page.value.page_num = pageInfo.page_num
  page.value.page_size = pageInfo.page_size
  if (formValue.value.label !== 'name') return
  nextTick(() => {
    userPageContentRef.value.getPageList(formValue.value, pageInfo)
  })
}

// 处理选择学院的逻辑（从store中获取学院列表，放入 teacherModelConfig 中的 college 选项即可）
watch(
  () => store.state.userManageModule.collegeList,
  (newVal) => {
    const collegeItem = teacherModelConfig.formItems.find((item) => item.field === 'college')
    collegeItem.options = newVal.map((item) => {
      return { title: item.college_name, value: item.college_name }
    })
  },
  {
    immediate: true
  }
)

// 导出事件
const onHandleDownloadClick = (title) => {
  store.dispatch('userManageModule/exportToExcelAction', {role: teacherFormConfig.userRole, title})
}

const [formModelRef, defualtModelFormData, onHandleEditClick, onHandleNewClick] = usePageModal()

onBeforeMount(() => {})
</script>

<style lang="less" scoped>
.teacher {
  padding: 10px;
}
</style>
